﻿using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Text;
using Xcj.Mes.Core.FileHelper;

namespace Xcj.Mes.Core.Logger
{
    public class DebugLogger : ILogger
    {
        private readonly string _logFilePath;

        public DebugLogger(string logFilePath = "")
        {
            _ = MyFileHelper.myFileHelper;
            if (string.IsNullOrEmpty(logFilePath))
            {
                string CurrentDisk = Environment.CurrentDirectory?.Substring(0, 2);
                string path = $"{CurrentDisk}\\电芯数据\\日志\\调试日志\\{DateTime.Now:yyyy年MM月}\\{DateTime.Now:yyyy年MM月dd日}";
                _logFilePath = $"{path}\\Run.log";
            }
            else
                _logFilePath = logFilePath;

            // 确保日志文件所在的目录存在
            try { Directory.CreateDirectory(Path.GetDirectoryName(_logFilePath)); } catch { }
        }

        public void Info(string message)
        {
            WriteLog("INFO", message);
        }

        public void Warning(string message)
        {
            WriteLog("WARNING", message);
        }

        public void Error(string message, Exception exception = null)
        {
            string fullMessage = message + (exception != null ? $"\nException: {exception}" : "");
            WriteLog("ERROR", fullMessage);
        }

        private void WriteLog(string level, string message)
        {
            try
            {
                string logEntry = $"{DateTime.Now:yyyy年MM月dd日 HH:mm:ss} [{level}] {message}";

                // 将日志信息追加到文件
                //File.AppendAllText(_logFilePath, logEntry + Environment.NewLine);
                if (!File.Exists(_logFilePath))
                    MyFileHelper.myFileHelper.CreateFile(_logFilePath, true, Encoding.UTF8);
                MyFileHelper.myFileHelper.Append(_logFilePath, logEntry + Environment.NewLine, Encoding.UTF8);
            }
            catch { }
        }

        void ILogger.Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter)
        {
            throw new NotImplementedException();
        }

        bool ILogger.IsEnabled(LogLevel logLevel)
        {
            throw new NotImplementedException();
        }

        IDisposable ILogger.BeginScope<TState>(TState state)
        {
            throw new NotImplementedException();
        }
    }
}
